#!user/bin/env python3
# -- coding: utf-8 --
# @Createtime：2022/6/9
# @Updatetime：21:53
# @Author：Test008
# @File：迭代器和生成器.py
# @Description：列表、元组、字典和集合都是可迭代的对象。它们是可迭代的容器，您可以从中获取迭代器（Iterator）。所有这些对象都有用于获取迭代器的 iter() 方法：
import os.path

mytuple = ("apple", "banana", "cherry")
myt = iter(mytuple)
print(next(myt))
print(next(myt))
print(next(myt))
print(''.center(50, '='))
mytuple = ["apple", "banana", "cherry"]
myt = iter(mytuple)
print(next(myt))
print('hello world')
print(next(myt))
print(next(myt))
print(''.center(50, '='))
# 而不是:for遍历无法控制，会被全部打印出来
for i in mytuple:
    print(i)
    print('hello world')

print(''.center(50, '='))
# 生成器
# 正常读取文件，一行行读取
path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'datafiles')
with open(path + './cookies.txt', 'r') as rfile:
    for line in rfile.readlines():
        print(line)

print(''.center(50, '='))


# 也可以写成：
def readfile():
    with open(path + './cookies.txt', 'r') as rfile:
        for lines in rfile.readlines():
            yield lines


# 加上next()可以一行行读取
data = readfile()
print(next(data))
print(next(data))
